package com.sk.rpcAssistNetty.io.netty.codec;

import com.sk.rpcAssistNetty.io.protocol.SerializeProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * description：
 *
 * @author 孙文斌
 * @Date: 2021/3/22 14:41
 */
public class RpcEncoder extends MessageToByteEncoder {

    private Class<?> clazz;
    private SerializeProtocol serializeProtocol;

    public RpcEncoder(Class<?> clazz, SerializeProtocol serializeProtocol) {
        this.clazz = clazz;
        this.serializeProtocol = serializeProtocol;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
//        System.out.println("netty 服务端encode被调用");
        if (clazz != null && clazz.isInstance(msg)) {
            byte[] bytes = serializeProtocol.serialize(msg);
            out.writeInt(bytes.length);
            out.writeBytes(bytes);
        }
    }
}
